var $CONFIG = {};

$CONFIG = {
	//HOST:'http://localhost/esyparking',
	HOST:'http://www.faceoz.com/adelaide',
	//HOST:'http://www.oversea.com.au/esyparking',
	searched:{
		TotalPages:0, //for recording the total pages
		revPage:0, //previous page on the showing result list
		zoom:18,
		CurrentPage:0, //current page on the showing result list
		TotalNums:0,  //for recording the total available nums 
		RowsPerpage:5,
		/**
		 * There are serveral places need to reset the current location
		 * - firstly loading the map
		 * - Click searching btn to fetch parks
		 * - Draging the map to asynly fecth the location
		 * - Click GPS locator 
		 */
		currLat:0,
		currLng:0,
		enableFladeOut:'Y',  //<- Here for Fan Liang usage change value to be 'N' or 'Y' to enable or diable the Faded Cover 
		loadingFlag:false
	},
	sqlPhase:{
		weekDay:0,  //the weekdays (0-6), 0 for sunday
		maxDuration:10,
		timeRange:0,
	},
	mapInit:{
		zoom:15,
		mapDiv:'#showMapArea',
		RsDiv:'.car-park-list',
		ParkItem:'.car-park',
		initArea:'CBD, Adelaide',
		suffix:'adelaide',
		initFlag:false
	},
	gpsInit:{
		gpsEnabled:false,
		gpsLat:'',
		gpsLng:''
	},
	flags:{
		loadDetails:false,
		everSearched:false
	},
	parkCatIcon:{
		FREE:'free-park.png',
		FEE:'fee-park.png'
	},
	constants:{
		userKey:'',
		currPHFlag:''
	},
	MarkerGrp:{
		DRAGING:'dragingGroup',
		SEARCHING:'searchingGroup',
		GPS:'myLocationGrp'
	},
	tmpMarkers:[]
	
};


/*
 * Some tips expression 
 */
$CONFIG['Invalids'] = 'Cant locate your posted address! Plesae retry another one!';
$CONFIG['ZERORESULT'] = 'There is no available parks around..';
/*
 * Global Map Object
 */
var $esyParkMapObj = {};


(function($){
	esypark = $.fn;
	esypark.extend({
		seachParkers:function(options){
			  var defaultSetting = {
					  input:'#goToAddress', /*THE INPUT DETECTED AREA*/
					  origText:'Location'
			  };
			  var option = $.extend(defaultSetting,options);
			  
			  var $colorConfig = {
					  focus:'#000',
					  blur:'#ccc' // <- here needs to be aligned with the css setting for element #searching input[type=text]
			  };
			  var $id = this.attr('id');
			  var $input = $(option.input);
			  var $ac;
			  
			  $('span#clearVal').css('left',($input.width() * 0.80)+'px').show().bind('click',function(){
				  $input.val('');
				  $input.focus();
				});
			  
			 
			  
			  $input.val(option.origText);
			  
			  //create listener for focus event
			  $input.bind('focus',function(){
					if($(this).val() == option.origText){
						$(this).val('');
					}
					$(this).css('color',$colorConfig.focus);
					

				    if($CONFIG.constants.userKey == 'N')
						  return;
					  
					clearTimeout($ac);
						 
					$ac = setTimeout(_fetchKeyword,500);
			 });
			  //create listener for keyup event
			  $input.bind('keyup',function(){
				  
				  if($CONFIG.constants.userKey == 'N')
					  return;
				  
				  clearTimeout($ac);
				 
				  $ac = setTimeout(_fetchKeyword,500);
			  });
			  
			  
			  $input.bind('blur',function(){
				if($(this).val() == ''){
					
					$(this).val(option.origText);	
				}
				$(this).css('color',$colorConfig.blur);
			  });
			 
			 $(option.input).bind('keydown',function(event){
				  if(event.keyCode==13){
					  $('#'+$id).trigger('click');
				   }
			  });
			  
			  this.bind('click',function(){
				  try{
						$esyParkMapObj.clearMarkers();
					}catch(e){
						
					}
				 $('#asyndiv').remove();
				 $CONFIG.flags.everSearched = true;
				 $(this).promptWindow();
				 if(($input.val() == option.origText)||($.trim($input.val())=='')){
					 $(this).promptMsg('Please input the address you would like to search!');
					 return;
				 }
				 
				 if($input.val().toLocaleLowerCase().indexOf("adelaide") < 0){
					 var inputVal = $.trim($input.val() + ' '+$CONFIG.mapInit.suffix);
				 }else{
					 var inputVal = $.trim($input.val());
				 }
				 /*
				  * Call the Google Map Geocoder API service to get the location
				  */
				 var geocoder = new google.maps.Geocoder();
				 geocoder.geocode({'address':inputVal,region:'au'},function(results, status){
						
						if(status == google.maps.GeocoderStatus.OK){
							try{
								$esyParkMapObj.clearMarkers();
							}catch(e){
								
							}
							
							var $latLng = results[0].geometry.location;
							var $lat = $latLng.lat();
							var $lng = $latLng.lng();
							//reset the current location
							$.thisSetLatLng($lat,$lng);
							
							if($lat && $lng){
								$esyParkMapObj.setMap({latitude:$lat,longitude:$lng,zoom:$CONFIG.searched.zoom});
								/*
								 * create the posted target location Marker
								 */
								$esyParkMapObj.createMarker({
									latitude:$lat,
									longitude:$lng,
									icon:$CONFIG.HOST+'/images/me.png',
									animation:'Y',
									html:{
										content:'Your Posted Location!',
										popup:false
									}
								});
							}else{
								return false;
							}
							//asyn to fetch the mapping records
							$(this)._fetchLocation({lat:$lat,lng:$lng});
							
							$(this)._SearchDone();
							if($CONFIG.constants.userKey != 'N'){
								$.ajax({
									type:'POST',
									url:$CONFIG.HOST+'/opt/cookies',
									cache:false,
									dataType:'json',
									data:{val:$.trim($input.val()),devid:$CONFIG.constants.userKey},
									success:function(data){
										
									}
								}); 
								 
							 }
							
							
						}
						else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
							alert($CONFIG['ZERORESULT']);
							$(this)._SearchDone();
							return false;
						}
						else{
							alert('Unexpected Error: '+status);
						}
						
				});
			 });
			 
			  function _fetchKeyword()
			  {
				  $.ajax({
						type:'POST',
						url:$CONFIG.HOST+'/opt/asynkeyword',
						cache:false,
						data:{key:$CONFIG.constants.userKey,val:$.trim($input.val())},
						dataType:'json',
						success:function(data){
							$('#asyndiv').remove();
							var str;
							var ext='';
							if(data.STATUS == 'OK'){
								var d = $("<div id='asyndiv'></div>");
								/*DROP DOWN THE JSON DATA*/
								for(var i in data.PARKER)
								{
									str += "<span>"+data.PARKER[i].WORD+"</span>";
								}
								
								d.appendTo('#searching').css('width',String(parseInt($input.css('width'))-2)+'px').show();
								
								$(str).appendTo(d);
							}
							
						},
						complete:function(){
							if($('#asyndiv').find('span').size()>0){
								$('#asyndiv').find('span').each(function(){
									$(this).bind('click',function(){
										$input.val($(this).html());
										$('#asyndiv').remove();
									})
								});
							}
						}
					});
			  }
		  },
		promptWindow:function(options){
				var defaultSetting = {
					barName:'', /*the title*/
					actionPath:'', /*the action properties of form*/
					formType:'log', /*determine which type of the prompted window*/
					extra:'',
					chkDiv:'cover' /*CAN USE THE ID WITH THE COVER AS PREFIX THEN WE COULD CREATE LOTS OF POP UP WINDOW*/
				};
				
				option = $.extend(defaultSetting,options);
				
				if(($('#'+option.chkDiv).attr('id')== undefined)){
					
					var $pd = $('<div></div>');
					$pd.attr('id',option.chkDiv);
					var $cd = $('<div></div>');
					$cd.attr('id','hiddAreaContent');
					//var $sd = $("<div class='title_bar'><span class='logo_sml'>"+option.barName+"</span><img src='"+$CONFIG.HOST+"/images/close.jpg' id='close' onClick='_closeCoverPicWin(\""+$pd.attr('id')+"\",\""+option.formType+"\")' ></div>");
					//$sd.appendTo($cd);
					$cd.appendTo($pd);
					switch(option.formType){
						case 'park':
							var $tableForm = $('<div></div>');$tableForm.attr('id','parkDetails').css({height:($(window).height()*0.8)+'px',width:($(window).width()*0.7)+'px'});
							var $sd = $("<div class='title_bar_h'><span class='logo_sml'></span><img src='"+$CONFIG.HOST+"/images/close.jpg' id='close' onClick='_closeCoverPicWin(\""+$pd.attr('id')+"\")' width='20' height='20'></div>");
							$sd.appendTo($tableForm);
							$("<div style='text-align:center;' id='parkContent'><img src='"+$CONFIG.HOST+"/images/loading.gif'> Loading ..</div>").appendTo($tableForm);
							break;
						default:
							var $tableForm = $("<div><img src='"+$CONFIG.HOST+"/images/loading.gif'></img> Searching ... Please wait ...</div>");
									
							break;
					}
					
					$tableForm.appendTo($cd);
					var $bd = $('<div></div>');
					$bd.attr('id','bgblack');
					$bd.appendTo($pd);
					$pd.appendTo('body');
					
					//check which is the bigger in order to let shadwo Div cover all the client page
					var shadwoHeight= ($(window).height() > document.body.clientHeight)? $(window).height():$(document.body).height();
					$bd.css({"width":$(window).width(),"height":shadwoHeight});
					$cd.goCenter();	
				}	
				else
				{
					//alert('click here');
					var shadwoHeight= ($(window).height() > document.body.clientHeight)? $(window).height():$(document.body).height();
					$('#bgblack').css({"width":$(window).width(),"height":shadwoHeight});
					
					$('#'+option.chkDiv).add('#hiddAreaContent').fadeIn(400);
				}
		},
		goCenter:function(){
			var top = ($(window).height() - this.height())/2;
			var left = ($(window).width() - this.width())/2;
			var scrollTop = $(document).scrollTop();
			var scrollLeft = $(document).scrollLeft();
			return this.css({position:'absolute',"top":top+scrollTop,left:left+scrollLeft});
		},
		promptMsg:function(e){
				//alert(e);
				$('#car-park-tips').html('');
				$($CONFIG.mapInit.RsDiv).empty();
				$('span#next').hide();
				$('span#prev').hide();
				$('#car-park-tips').html(e);
				$(this)._SearchDone();
				return this;
			},	
		adjustClientMapMetric:function(options){
			//default to align to the client browser's window
				var $winObj = {
						width:$(window).width(), 
						height:$(window).height()
				 };
				var  option = $.extend($winObj,options);
				var pre = Math.round((1-($('#searching').height()/option.height))*option.height)-10;
				//alert(pre);
				$(this).css({
					//height:$(window).height(),
					height:pre+'px',
					width:option.width+'px'
				});
		},
		changeAppearance:function(e){
			var animatePath = {
					obj:'#showresult', //the targeted DIV to do the animation
					pos:'left', //the direction
					dis:$('#showresult').css('width'),//the distance
					animation:'N'
			};
			var $params = $.extend(animatePath,e);
			
			var $bgPosition = {left:'left -74px',right:'left -29px',top:'left -118px',bottom:'left top'};
			$($params.obj).css('left','-'+$params.dis);
			$(this).toggle(function(){
				switch($params.pos){
				case 'left':
					$params.animation == 'Y'? $($params.obj).animate({left:'0px'},1000):$($params.obj).css('left','0px');
					$(this).css('background-position',$bgPosition.left);
					break;
				case 'top':
					$params.animation == 'Y'? $($params.obj).animate({top:'0px'},1000):$($params.obj).css('top','0px');
					$(this).css('background-position',$bgPosition.top);
					break;
				}},
				function(){
				switch($params.pos){
					case 'left':
						$params.animation == 'Y'? $($params.obj).animate({left:'-'+$params.dis},1000):$($params.obj).css('left','-'+$params.dis);
						$(this).css('background-position',$bgPosition.right);
						break;
					case 'top':
						$params.animation == 'Y'? $($params.obj).animate({top:'-'+$params.dis},1000):$($params.obj).css('top','-'+$params.dis);
						$(this).css('background-position',$bgPosition.bottom);
						break;
				}
				
			
			}	
			);
		},
		/**
		 * Main function for the asynchronous searching the parkings through params 
		 * @param options{latitude & longitude}
		 */
		_fetchLocation:function(options){
			var defaultSetting = {
				lat:'',  //the center latitude
				lng:'',
				drag:'N', //to define whether they need to append to the searching list
				page:'' //detecting whether it is going to change the page
			};
			var e = $.extend(defaultSetting,options);
			
			//var counter = $CONFIG.flags.loadDetails + 1;
			
			$CONFIG.searched.loadingFlag = true;
			
			if(e.drag == 'Y'){
				if($CONFIG.flags.everSearched == false){
					//if user never press the search btn then searched the details by default
					var $paramsPassing = {
							lat:e.lat.toFixed(6),
							lng:e.lng.toFixed(6),
							fee:$('#fee-type').find('option:selected').val(),
							hrs:$('#park-hrs').find('option:selected').val(),
							mins:$('#park-mins').find('option:selected').val(),
							parktime:$('#park-time').find('option:selected').val(),
							weekday:$CONFIG.sqlPhase.weekDay
						};
				}
				else{
					//if user ever searched once through the btn then use the sessions 
					var $paramsPassing = {
							lat:e.lat.toFixed(6),
							lng:e.lng.toFixed(6),
							drag:'Y'
							};
				}
				if($CONFIG.searched.enableFladeOut == 'Y'){
					 $(this).promptWindow();
				}
			}
			else{
				/**
				 * the select event has been added @ Mar 19,2013
				 */
				if(e.drag == 'select'){
					$(this).promptWindow();
					try{
						$esyParkMapObj.clearMarkers();
					}catch(e){
						
					}
					
				}
				var $paramsPassing = (e.page =='')?{
					lat:e.lat.toFixed(6),
					lng:e.lng.toFixed(6),
					fee:$('#fee-type').find('option:selected').val(),
					hrs:$('#park-hrs').find('option:selected').val(),
					mins:$('#park-mins').find('option:selected').val(),
					parktime:$('#park-time').find('option:selected').val(),
					weekday:$CONFIG.sqlPhase.weekDay
					}:{page:e.page};
				$CONFIG.sqlPhase.maxDuration = $paramsPassing.parktime;
				$CONFIG.sqlPhase.timeRange = String($paramsPassing.hrs)+String($paramsPassing.mins);
			}
			
			
			$.ajax({
					type:'POST',
					url:$CONFIG.HOST+'/opt/searching',
					cache:false,
					dataType:'json',
					data:$paramsPassing,
					success:function(data){

						if(e.drag != 'Y'){
							if(data.STATUS == 'OK'){
								$('#car-park-tips').html('');
								$CONFIG.searched.TotalPages = data.TOTAL_PAGE;
								$CONFIG.searched.TotalNums = data.TOTAL_NUMS;
								$CONFIG.searched.CurrentPage = data.CURR_PAGE;
								
								$.pageSetting();
								
								if(e.page ==''){
									$($CONFIG.mapInit.RsDiv).empty();
								}else if($CONFIG.searched.revPage >= 0){
									$('div[id^=page-]').each(function(){
										$(this).hide();
									});
									
								}
									
								var objDiv = '<div id="page-'+$CONFIG.searched.CurrentPage+'">';
								var flag = $CONFIG.searched.CurrentPage;
								for (var i in data.PARKS){
									if((i % $CONFIG.searched.RowsPerpage==0)&& (i>0)){
										flag++;
										objDiv += '</div><div id="page-'+flag+'">';
									}
									objDiv += "<div class='car-park' alt='"+data.PARKS[i].LAT+"_"+data.PARKS[i].LNG+"_"+data.PARKS[i].ID+"_"+data.PARKS[i].TOTAL+"_"+data.PARKS[i].FEE+"' title='"+data.PARKS[i].NOTES+"'>"+data.PARKS[i].ADDRESS+"</div>";
								}
								objDiv += '</div>';
								$(objDiv).appendTo($CONFIG.mapInit.RsDiv);
								$('#page-'+$CONFIG.searched.CurrentPage).show();
							}else if(data.STATUS == 'ZERO_RESULTS'){
								$CONFIG.searched.TotalPages = data.TOTAL_PAGE;
								$CONFIG.searched.TotalNums = data.TOTAL_NUMS;
								//$CONFIG.searched.CurrentPage = data.CURR_PAGE;
								$.pageSetting({curr:0});
								$($CONFIG.mapInit.RsDiv).empty();
								//$esyParkMapObj.clearMarkers();
								$('#car-park-tips').html($CONFIG['ZERORESULT']);
							}
						}else{
							//triggered by dragging
							if(data.STATUS == 'OK'){
								$CONFIG.searched.TotalNums = data.TOTAL_NUMS;
								var counter = 0;
								for (var i in data.PARKS){
									
									counter++;
									var $idd = 'dragParkers-'+data.PARKS[i].ID;
									var $iddE = 'parkers-'+data.PARKS[i].ID;
									
									var $icon = (data.PARKS[i].FEE=='Y')?$CONFIG.parkCatIcon.FEE:$CONFIG.parkCatIcon.FREE;
									if(jQuery.inArray($idd,$esyParkMapObj.getMarkers('group',$CONFIG.MarkerGrp.DRAGING)) < 0 && jQuery.inArray($iddE,$esyParkMapObj.getMarkers('group',$CONFIG.MarkerGrp.SEARCHING)) < 0){
										
										$esyParkMapObj.createMarker({  
									 		latitude: data.PARKS[i].LAT,
									 		longitude:data.PARKS[i].LNG,
								            title:data.PARKS[i].ADDRESS,
								            id:$idd,
								            icon:$CONFIG.HOST+'/images/'+$icon,
								            counter:{
								            	curr:counter,
								            	total:$CONFIG.searched.TotalNums
								            },
								            group:$CONFIG.MarkerGrp.DRAGING
								           /*
								             ,html: { 
								                content: "<div style='text-align:center;position:relative;margin-top:-50px;'><img src='"+$CONFIG.HOST+"/images/loading.gif'> Loading ..</div>", 
								                popup: false 
								            }
								            */ 
										}); 
	
									}else{
										
										/****
										 * Added a hidding group to well contorl the status to show the markers
										 */
										$esyParkMapObj.createMarker({  
									 		latitude: data.PARKS[i].LAT,
									 		longitude:data.PARKS[i].LNG,
									 		visible:false,
								            counter:{
								            	curr:counter,
								            	total:$CONFIG.searched.TotalNums
								            },
								            group:'hiddingGroup'
										}); 
									}
									
								}//for
								
							}else{
								$('#loading').hide();
							}
						}
					},
					complete:function(){
						$CONFIG.searched.loadingFlag = false;
						
						if(e.drag != 'Y'){
							
							if($($CONFIG.mapInit.RsDiv).find($CONFIG.mapInit.ParkItem).size() > 0 ){
								var totalNum = $($CONFIG.mapInit.RsDiv).find($CONFIG.mapInit.ParkItem).size();
								/**
								 * See if there is any result found,then create markers
								 */
								var flagCurr = 0;
								 $($CONFIG.mapInit.RsDiv).find($CONFIG.mapInit.ParkItem).each(function(){
									 /**
									  * the propery `alt` format: latitude[0]_longitude[1]_Park ID[2]_ParkPosition[3]_ParkFeeType_[4]
									  */
									 var currAddress = $(this).html();
									 flagCurr++;
									 var $tmpArr = $(this).attr('alt').split('_');
									 var $notes = $(this).attr('title');
									 var $icon = ($tmpArr[4]=='Y')?$CONFIG.parkCatIcon.FEE:$CONFIG.parkCatIcon.FREE;
									 $esyParkMapObj.createMarker({  
										 		latitude: $tmpArr[0],
										 		longitude:$tmpArr[1],
									            title:currAddress,
									            id:'parkers-'+$tmpArr[2],
									            counter:{
									            	curr:flagCurr,
									            	total:totalNum
									            },
									            group:$CONFIG.MarkerGrp.SEARCHING,
									            icon:$CONFIG.HOST+'/images/'+$icon
									            /*
									            ,html: { 
									                content:"<div style='text-align:center;position:relative;margin-top:-50px;'><img src='"+$CONFIG.HOST+"/images/loading.gif'> Loading ..</div>", 
									                popup: false 
									            }
									            */ 
									    }); 
									 /**
									  * Create click event for those parks
									  * we need to specify those markers on the searching list other than those created by dragging
									  */ 
									 
									 $(this).bind('click',function(){
										 var $index = $($CONFIG.mapInit.RsDiv).find($CONFIG.mapInit.ParkItem).index($(this));
										 var $mappingMarkers = $esyParkMapObj.getMarkers('group',$CONFIG.MarkerGrp.SEARCHING);
										// if($($esyParkMapObj.mapId).data($mappingMarkers[$index]+'info').show == false){
											 google.maps.event.trigger($($esyParkMapObj.mapId).data($mappingMarkers[$index]),'click');
									//	 }
										 $('span#btn').trigger('click');
									 });
								 });
							}
					}
					
					if(e.drag == 'select'){
						$(this)._SearchDone();
					}else
					$('#cover').fadeOut();
				  } //complete
			  });
		},
		//differ the color via odd/even tr
		colorfulTableTr:function(options){
				//default classes for different rows
				var defaultSetting = {
					odd:'shadow',
					even:''
				}
				//override the default ones if some params are passed 
				option = $.extend(defaultSetting,options);
				
				$("tbody > tr:odd" ,this).addClass(option.odd);
				$("tbody > tr:even",this).addClass(option.even);
				
				return this;
			},
	   _SearchDone:function(e){
		   var defSetting = {
				  div:'cover'//the div name which to be fadeOut
		   };
		   $('#asyndiv').remove();
		   var options = $.extend(defSetting, e);
		   $('#'+options.div).fadeOut();
		   if(parseInt($('#showresult').css('left')) < 0)
			   $('span#btn').trigger('click');
	   }
	});
	$.extend({
		 getCurrentLocation:function(){
			    $esyParkMapObj.clearMarkers();
			  
			    var lat = 0;
			    var lng= 0;
			    

				if($esyParkMapObj.getMarkers('group',$CONFIG.MarkerGrp.GPS).length>0){
					$.goMap.showHideMarker('GPSLocation');
				}
				
			    
			    if($CONFIG.gpsInit.gpsEnabled == false){
			    		navigator.geolocation.watchPosition(function(position){
							$CONFIG.gpsInit.gpsLat = position.coords.latitude;
							$CONFIG.gpsInit.gpsLng = position.coords.longitude;
							$CONFIG.gpsInit.gpsEnabled = true;
							$('#texting').html('Current Lat:'+$CONFIG.gpsInit.gpsLat+' ; Lng:'+$CONFIG.gpsInit.gpsLng);

							lat = $CONFIG.gpsInit.gpsLat;
							lng = $CONFIG.gpsInit.gpsLng;
							
							$esyParkMapObj.createMarker({
									latitude:lat,
									longitude:lng,
									icon:$CONFIG.HOST+'/images/me.png',
									animation:'Y',
									id:'GPSLocation',
									group:$CONFIG.MarkerGrp.GPS,
									html:{
										content:'You are here!', 
						                popup: false 
									}
								});
						
							
							$esyParkMapObj.setMap({
								latitude:lat,
								longitude:lng
							});
							$.thisSetLatLng(lat,lng);
							$('span#btn')._fetchLocation({lat:lat,lng:lng});
						},function(error){
						//	$(this).promptMsg('Sorry, we cant get your location ..');
							$(this)._SearchDone();
						},{
							//enable the high acuracy for the gps location 
							enableHighAcuracy:true,
							timeout:15000,
							maximumAge:1000
						});
			    }
			    else{
			    		lat = $CONFIG.gpsInit.gpsLat;
						lng = $CONFIG.gpsInit.gpsLng;
						//console.log('Current Lat:'+$CONFIG.gpsInit.gpsLat+' ; Lng:'+$CONFIG.gpsInit.gpsLng);
					  
						
						$esyParkMapObj.createMarker({
								latitude:lat,
								longitude:lng,
								icon:$CONFIG.HOST+'/images/me.png',
								animation:'Y',
								id:'GPSLocation',
								group:$CONFIG.MarkerGrp.GPS,
								html:{
									content:'You are here!', 
					                popup: false 
								}
							});
					
						
						$esyParkMapObj.setMap({
							latitude:lat,
							longitude:lng
						});
						$.thisSetLatLng(lat,lng);
						$('span#btn')._fetchLocation({lat:lat,lng:lng});
			    }
			   
				
			   
		},
		appendJS:function(){
			document.write('<script language=javascript src="'+$CONFIG.HOST+'/javascript/jquery.gomap.js?V=2dsdadf"></script>');
		},
		showPosition:function(position){
			//var latlon=position.coords.latitude+","+position.coords.longitude;
			try{
				var lat = position.coords.latitude;
				var lng = position.coords.longitude;
				//$esyParkMapObj.clearMarkers();
				
				if($esyParkMapObj.getMarkers('group',$CONFIG.MarkerGrp.GPS).length>0){
					$.goMap.showHideMarker('GPSLocation');
				}
				
				$esyParkMapObj.createMarker({
						latitude:lat,
						longitude:lng,
						icon:$CONFIG.HOST+'/images/me.png',
						animation:'Y',
						id:'GPSLocation',
						group:$CONFIG.MarkerGrp.GPS,
						html:{
							content:'You are here!', 
			                popup: false 
						}
					});
			
				
				$esyParkMapObj.setMap({
					latitude:lat,
					longitude:lng
				});

				
				$(this)._SearchDone();
				//$('span#btn').trigger('click');	
			}catch(e){
				
				$(this)._SearchDone();
				// $('span#btn').trigger('click');	
				// alert(e);
			}
			
			$(this)._fetchLocation({lat:lat,lng:lng});
		},
		initialSysTime:function(){
			   var myDate = new Date();
			   var hrs = myDate.getHours();   
			   var mins = myDate.getMinutes();
			   var day = myDate.getDay();  //(0-6,0 for sunday,8 for public holiday)
			   $('#park-hrs').find('option[id=hrs-'+hrs+']').attr('selected','selected');
			   $('#park-mins').find('option[id=min-'+mins+']').attr('selected','selected');
			   $CONFIG.sqlPhase.weekDay = ($CONFIG.constants.currPHFlag=='N')? day : parseInt($CONFIG.constants.currPHFlag);
			  
			   $CONFIG.sqlPhase.timeRange = String(hrs)+String(mins);
		},
		init:function(options){
			
			//if($CONFIG.mapInit.initFlag == true) return;
			//$CONFIG.mapInit.initFlag = true;
			 var myMap = $.extend($CONFIG,options);
			
			 $.initialSysTime();
			
			 $($CONFIG.mapInit.mapDiv).adjustClientMapMetric();
			 var currAddress;
			 var currAddressTitle;
			 var countFlag = 0;
			 
			 /**
			  * Default to show the center of the city @ Cavin ,Mar 26
			  */
			$($CONFIG.mapInit.mapDiv).goMap({
					 address:$CONFIG.mapInit.initArea  ,
					 maptype: 'ROADMAP',
					 icon:$CONFIG.HOST+'/images/me.png',
					 zoom:$CONFIG.mapInit.zoom,
					 disableDoubleClickZoom:true,
					 navigationControlOptions: { 
				            position: 'BOTTOM', 
				            style: 'ANDROID' 
				        },
				     hideByClick: true 
				}); 
			 
			$('body')._fetchLocation({lat:$CONFIG.searched.currLat,lng:$CONFIG.searched.currLng});
			 $esyParkMapObj = $.goMap;

			
			$('body').bind('click',function(){
				$('#asyndiv').remove();
			}); 
			 
			$esyParkMapObj.createListener({type:'map'}, 'click', function(event) { 
				 $esyParkMapObj.clearInfo();  $('#asyndiv').remove();
				 if(parseInt($('#showresult').css('left'))>=0)
					 $('span#btn').trigger('click');
			}); 
			$('#goToMap').seachParkers(); 
			
			//$('span#btn-top').changeAppearance({obj:'#searching',pos:'top',dis:(parseInt($('#searching').css('height'))+20)+'px'}); 
			
			$('span#next').bind('click',function(){
				if($('#page-'+(parseInt($CONFIG.searched.CurrentPage)+1)).attr('id')!=undefined){
					$('div[id^=page-]').each(function(){
						$(this).hide();
					});
					$('#page-'+(parseInt($CONFIG.searched.CurrentPage)+1)).show();
					$CONFIG.searched.CurrentPage = (parseInt($CONFIG.searched.CurrentPage)+1);
					$.pageSetting();
				}else
					$(this)._fetchLocation({page:(parseInt($CONFIG.searched.CurrentPage)+1)});
			});
			
			$('span#prev').bind('click',function(){
				if($('#page-'+$CONFIG.searched.revPage).attr('id')!=undefined){
					$('div[id^=page-]').each(function(){
						$(this).hide();
					});
					$('#page-'+$CONFIG.searched.revPage).show();
					$CONFIG.searched.CurrentPage = (parseInt($CONFIG.searched.CurrentPage)-1);
					$.pageSetting();
				}else
					$(this)._fetchLocation({page:(parseInt($CONFIG.searched.CurrentPage)-1)});
				
			});
			
			var $timer;
			$esyParkMapObj.createListener({type:'map'},'dragend',function(event){
				/*
				 * modified at Mar 19th by Cavin
				 * following is purely control the times of the event triggers
				 */
				//$.triggerDragingTimer();
				if($CONFIG.searched.loadingFlag == true){
					return;
				}
				
				if($CONFIG.searched.enableFladeOut == 'Y'){
					$('#loading').show();
					   var newLatLng = $esyParkMapObj.getMap().getCenter();
					   var $lat = newLatLng.lat();
					   var $lng = newLatLng.lng();
					   //reset the current location
					   $.thisSetLatLng($lat,$lng);
						
					   $(this)._fetchLocation({
							lat:$lat,
							lng:$lng,
							drag:'Y'
						});
						if(parseInt($('#showresult').css('left'))>=0)
							$('span#btn').trigger('click');
				}else{
					clearTimeout($timer);
					$timer = setTimeout($.triggerDragingTimer,1000);
				}
			});
			
			/**
			 * Once the GPS enabled then searching the parks around the current location by default
			 * Cavin @ Mar 15,2013
			 * futher commented at Mar 26
			if($CONFIG.gpsInit.gpsEnabled){
				//$esyParkMapObj.clearMarkers();
				$('body')._fetchLocation({lat:$CONFIG.gpsInit.gpsLat,lng:$CONFIG.gpsInit.gpsLng});
			}
			 */
			$('.expandedContent .title_bar').live('click',function(){
					 
					 var $index = $('.expandedContent').children('.title_bar').index($(this));
					 var $id = $(this).attr('alt');
					 var $cat = $(this).attr('name');
					 var $currentTar = $('.expandedContent').children('.title_bar:eq('+$index+')');
					 var $contentDIV = $('#expandedContent-list-'+$cat+'-'+$id);

					 if($contentDIV.attr('id')==undefined){
						 /**
						  * See if the content has been fetched before
						  */
						// if($CONFIG.flags.loadDetails) return;
						// $CONFIG.flags.loadDetails = true;
						
					 }else{
						 $contentDIV.colorfulTableTr();
						 $CONFIG.flags.loadDetails = false;
						 $('.expandedContent').find('div[id^=expandedContent-list-]').each(function(){
							if($(this).attr('id') == $contentDIV.attr('id')){
								
							}else
								//$(this).hide();
								$(this).slideUp();
						 });
						 if($contentDIV.css('display')=='none'){
							 $contentDIV.slideDown();
							// $contentDIV.show();
						 }else{
							 $contentDIV.slideUp();
							// $contentDIV.hide();
						 }
					 }
				
					 
			 }); // $('.expandedContent .title_bar')
			
			$('select').bind('change',function(){
				if($CONFIG.searched.currLat == 0 || $CONFIG.searched.currLng==0){
					return;
				}
				$(this)._fetchLocation({
					lat:$CONFIG.searched.currLat,
					lng:$CONFIG.searched.currLng,
					drag:'select'
				});
			});
						
		},
		pageSetting:function(e){
			 var defaultSetting = {
					 curr:$CONFIG.searched.CurrentPage,
			 };
			 var $options = $.extend(defaultSetting, e);
			 $CONFIG.searched.revPage = ($options.curr > 1)?$options.curr-1:0;
			 if((parseInt($CONFIG.searched.CurrentPage) == parseInt($CONFIG.searched.TotalPages))||(parseInt($CONFIG.searched.TotalPages)==0)){
					$('span#next').hide();
				}else{
					$('span#next').show();
				}
				
			if($CONFIG.searched.revPage == 0||(parseInt($CONFIG.searched.TotalPages)==0)){
					$('span#prev').hide();
				}else{
					$('span#prev').show();
			}
				
		}
		,thisSetLatLng:function(lat,lng){
			$CONFIG.searched.currLat = lat;
			$CONFIG.searched.currLng = lng;
		}
		,triggerDragingTimer:function(){
			   $('#loading').show();
			   var newLatLng = $esyParkMapObj.getMap().getCenter();
			   var $lat = newLatLng.lat();
			   var $lng = newLatLng.lng();
			   //reset the current location
			   $.thisSetLatLng($lat,$lng);
			   $(this)._fetchLocation({
					lat:$lat,
					lng:$lng,
					drag:'Y'
				});
				if(parseInt($('#showresult').css('left'))>=0)
					$('span#btn').trigger('click');
		}
	});
})(jQuery);



if(navigator.geolocation){
	navigator.geolocation.watchPosition(function(position){
		$CONFIG.gpsInit.gpsLat = position.coords.latitude;
		$CONFIG.gpsInit.gpsLng = position.coords.longitude;
		$CONFIG.gpsInit.gpsEnabled = true;
		//reset the current location
		$.thisSetLatLng($CONFIG.gpsInit.gpsLat,$CONFIG.gpsInit.gpsLng);
		
		if($('#GPS').attr('id') == undefined){
			$('<span id="GPS"></span>').appendTo('body').bind('click',function(){
		    	$(this).promptWindow();
		    	$.getCurrentLocation();
		    });
		}
	},function(error){
		
		if($('#GPS').attr('id') == undefined){
			$('<span id="GPS"></span>').appendTo('body').bind('click',function(){
		    	$(this).promptWindow();
		    	$.getCurrentLocation();
		    });
		}

	},{
		//enable the high acuracy for the gps location 
		enableHighAcuracy:true,
		timeout:1000,
		maximumAge:10000
	});
}




$.appendJS();$('span#btn').changeAppearance();

function _closeCoverPicWin(id)
{
	$('#'+id).hide().remove();
}

